// import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Button,Cascader, Col, Form, Input, Row, Select, theme, Divider, Radio, Table, Space, Tag, Checkbox, Modal ,DatePicker ,Switch, Upload,message } from 'antd';
import { useEffect, useState } from 'react';
import './index.scss'
import http from '../../../utils/fetchHttp'
import { PlusOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';


// 搜索表单
const AdvancedSearchForm = (props) => {
    const {date,setDate}=props
    const { RangePicker } = DatePicker;
    const [sex, setSex] = useState('男');
    const [data, setData] = useState('');
    const [imgurl,setImgurl]=useState('')
    const { token } = theme.useToken();
    const [form] = Form.useForm();
    const [form1] = Form.useForm();
    const [expand, setExpand] = useState(false);
    
    const formStyle = {
        maxWidth: 'none',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        padding: 10,
    };

    // 点击筛选后的数据及请求
    const onFinish = (values) => {
        console.log('Received values of form: ', values,data,values.userName,values.userId);
        http({
            url:'/user/searchUser',
            method: 'post',
            data:{
                user_name:values.userName,
                user_id:values.userId,
                user_creattime:data,

            }
        }).then((res=>{
            console.log(res);
            if(res.code==200){
                setDate(res.data)
            }
        
        }))
    };
    const onChange = (date, dateString) => {
        console.log(dateString);
        setData(dateString)
      };
    //模态框
    const [open, setOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    // 添加
    const showModal = () => {
      setOpen(true);
    };
    const handleCancel = () => {
      console.log('Clicked cancel button');
      setOpen(false);
    };
    const showUpload=(info)=>{
        if (info.file.status === 'done') {
            console.log(info.file);
            setImgurl(info.file.response)
        }
       
    }
    //获取现在的时间
    function timestampToTime(times) {
        let time = times[1]
        let mdy = times[0]
        mdy = mdy.split('/')
        let month = parseInt(mdy[0]);
        let day = parseInt(mdy[1]);
        let year = parseInt(mdy[2])
        return year + '-' + month + '-' + day + ' ' + time
    }
    let time = new Date()
    let nowTime = timestampToTime(time.toLocaleString('en-US',{hour12: false}).split(" "))
    //重置
    const getAllList=()=>{
        http({
            url:'/user/getUerList',
            method: 'get',
        }).then((res=>{
            console.log(res);
            if(res.code==200){
                setDate(res.data)
            }
        
        }))
    }

   
    //添加用户
    const addFinish=async () => {
        const values = await form1.validateFields();
        http({
            url:'/user/addUser',
            method: 'post',
            data:{
                user_name:values.user_name,
                user_emails:values.user_emails,
                user_pwd:values.user_emails.match( /^[^.]*(?=@)/),
                user_phone:values.user_phone,
                user_address:values.user_address,
                user_birthday:data,
                user_img:imgurl,
                user_sex:sex,
                user_creattime:nowTime
            }
        }).then((res)=>{
            if(res.code==200){
                message.success('用户添加成功')
                http({
                    url:'/user/getUerList',
                    method: 'get',
                }).then((res=>{
                    console.log(res);
                    if(res.code==200){
                        setDate(res.data)
                    }
                
                }))
                setOpen(false);
            }
           else if(res.code==500){
            message.error('用户添加失败')
            setOpen(false);
           }
        })
      };
      const onChangeSex = (e) => {
        console.log('radio checked', e.target.value);
        setSex(e.target.value);
      };
      const dateFormat = 'YYYY-MM-DD';
    return (
        <Form form={form} name="advanced_search" style={formStyle} onFinish={onFinish}>
            <Row gutter={22} >
                 <Col span={6} className={'search'}>
                    <Form.Item
                        name='userId'
                        label='用户id'
                        rules={[
                            {
                                message: '请输入用户id',
                            },
                        ]}
                    >
                        <Input placeholder="请输入用户id" />
                    </Form.Item>
                </Col>
                <Col span={6} className={'search'} >
                    <Form.Item
                        name='userName'
                        label='用户姓名'
                        rules={[
                            {
                                message: '请输入用户姓名',
                            },
                        ]}
                    >
                        <Input placeholder="请输入用户姓名" />
                    </Form.Item>
                </Col>
                <Col span={6} className={'search'}>
                    <Form.Item
                        name='creatTime'//初始化动态变得数据
                        label='创建时间'
                    >
                        <Space direction="vertical">
                            <DatePicker onChange={onChange} />
                        </Space>
                    </Form.Item>
                </Col>
            </Row>
            <Row> 
                <Col
                    span={22}
                    style={{
                        // textAlign: 'right',
                    }}
                >
                    <Button type="primary" style={{
                            margin: '0 0.8rem',
                        }} onClick={showModal}>
                        添加
                    </Button>
                    <Modal
                        title="添加用户"
                        open={open}
                        // onOk={handleOk}
                        confirmLoading={confirmLoading}
                        // onCancel={handleCancel}
                        footer={[
                            <Button key='submit' type="primary" htmlType="submit" onClick={addFinish}>
                               添加
                              </Button>,
                              <Button key='cancel' htmlType="button" onClick={handleCancel} style={{ marginLeft: "10px" }}>
                                取消
                              </Button>
                          ]}
                    >
                        <Form
                            form={form1}
                            labelCol={{
                            span: 4,
                            }}
                            wrapperCol={{
                            span: 14,
                            }}
                            layout="horizontal"
                            style={{
                            maxWidth: 600,
                            }}
                           
                        >
                            <Form.Item label="用户名称" name='user_name'>
                            <input />
                            </Form.Item>
                            <Form.Item label="用户账号" name='user_emails'>
                            <input/>
                            </Form.Item>
                            <Form.Item label="手机号" name='user_phone'>
                            <input/>
                            </Form.Item>
                            <Form.Item label="地址" name='user_address'>
                            <input/>
                            </Form.Item>
                            <Form.Item label="生日" name='user_birthday'  >
                            <DatePicker format={dateFormat} onChange={onChange} />
                            </Form.Item>
                            <Form.Item label="性别" >
                            <Radio.Group onChange={onChangeSex} value={sex}>
                                <Radio value={'男'}>男</Radio>
                                <Radio value={'女'}>女</Radio>
                                
                            </Radio.Group>
                            </Form.Item>
                            <Form.Item label="上传头像" valuePropName="fileList">
                            <Upload action="/api/upload" onChange={showUpload} listType="picture-card"  >
                                <div>
                                <PlusOutlined />
                                <div
                                    style={{
                                    marginTop: 8,
                                    }}
                                >
                                    头像
                                </div>
                                </div>
                            </Upload>
                            </Form.Item>
                        </Form>
                    </Modal>
                    <Button type="primary" htmlType="submit"
                    >
                        筛选
                    </Button>
                    <Button
                        style={{
                            margin: '0 .8rem',
                        }}
                        onClick={() => {
                            form.resetFields();
                            getAllList()
                        }}
                    >
                        重置
                    </Button>
                    
                </Col>
            </Row>
        </Form>
    );
};
// ----以下是表格
// 表格


const TableDetail = (props) => {
    const {date,setDate}=props
    const { RangePicker } = DatePicker;
    const [data, setData] = useState(undefined);
    const [form2] = Form.useForm();
    const [sex, setSex] = useState('男');
    const [imgurl,setImgurl]=useState('')
    const [componentDisabled, setComponentDisabled] = useState(true);
    const [user_name,setUser_name]=useState('')
    const [user_phone,setUser_phone]=useState('')
    const [user_address,setUser_address]=useState('')
    const [user_id,setUser_id]=useState('')
    const [user_email,setUser_email]=useState('')
    const [btn,setBtn]=useState("none")
    const [fileList, setFileList] = useState([{
        url:''
    }])
    //模态框
    const [lookOpen, setlookOpen] = useState(false);
    const [confirmLoading, setConfirmLoading] = useState(false);
    //
    form2.setFieldsValue({
        user_name,
        user_email,
        user_phone,
        user_address,
	})
    // 查看
    const handleCancel = () => {
      console.log('Clicked cancel button');
      setlookOpen(false);
    };
    const showUpload=(info)=>{
        if (info.file.status === 'done') {
            console.log(info.file.response);
            setImgurl(info.file.response)
        }
       
    }
    const onChange = (date, dateString) => {
        console.log(dateString);
        setData(dateString)
      };
    //获取现在的时间
    function timestampToTime(times) {
        let time = times[1]
        let mdy = times[0]
        mdy = mdy.split('/')
        let month = parseInt(mdy[0]);
        let day = parseInt(mdy[1]);
        let year = parseInt(mdy[2])
        return year + '-' + month + '-' + day + ' ' + time
    }
    let time = new Date()
    let nowTime = timestampToTime(time.toLocaleString('en-US',{hour12: false}).split(" "))
    const showRow=(record)=>{
        console.log('查看',record);
        setUser_name(record.user_name)
        setUser_address(record.user_address)
        setUser_email(record.user_email)
        setUser_phone(record.user_phone)
        setData(record.user_birthday)
        if(record.user_sex==0){
            setSex('男')
        }else{
            setSex('女')
        }
        setFileList([{
            url:'/api'+record.user_img
        }])
        setImgurl(record.user_img)
        console.log(user_name,imgurl,data);
        setComponentDisabled(true)
        setlookOpen(true);
    }
    const detailRow=(record)=>{
        console.log('编辑',record,record.user_birthday,data,sex);
        setBtn("")
        setUser_name(record.user_name)
        setUser_address(record.user_address)
        setUser_email(record.user_email)
        setUser_phone(record.user_phone)
        setUser_id(record.user_id)
        setData(record.user_birthday)
        if(record.user_sex==0){
            setSex('男')
        }else{
            setSex('女')
        }
        setFileList([{
            url:'/api'+record.user_img
        }])
        setImgurl(record.user_img)
        setComponentDisabled(false)
        setlookOpen(true);
    }
    const detailFinish=async () => {
        const values = await form2.validateFields();
        console.log(values,data,imgurl,sex);
        console.log(user_id);
        http({
            url:'/user/detailUser',
            method: 'post',
            data:{
                user_id,
                user_name:values.user_name,
                user_emails:values.user_email,
                user_phone:values.user_phone,
                user_address:values.user_address,
                user_birthday:data,
                user_img:imgurl,
                user_sex:sex,
            }
        }).then((res=>{
            if(res.code==200){
                message.success('用户更改成功')
                setlookOpen(false);
                getUerList()
            }
           else if(res.code==500){
            message.error('用户更改失败')
           }
        
        }))
    }
    const delRow=(record)=>{
        console.log('删除',record);
        http({
            url:'/user/deleteUser',
            method: 'post',
            data:{
                user_id:record.user_id
            }
        }).then((res=>{
            if(res.code==200){
                message.success('用户删除成功')
                getUerList()
            }
           else if(res.code==500){
            message.error('用户删除失败')
           }
        
        }))
    }
    const getUerList=()=>{
        http({
            url:'/user/getUerList',
            method: 'get',
        }).then((res=>{
            console.log(res);
            if(res.code==200){
                setDate(res.data)
            }
        
        }))
    }
    const onChangeSex = (e) => {
        console.log('radio checked', e.target.value);
        setSex(e.target.value);
      };
    const dateFormat = 'YYYY-MM-DD';
    useEffect(()=>{
        getUerList()
    },[])
    
    const columns = [
        {
            title: '序号',
            dataIndex: 'user_id',
            key: 'user_id',
        },
        {
            title: '用户名称',
            dataIndex: 'user_name',
            key: 'user_name',
        },
        {
            title: '用户账户',
            dataIndex: 'user_email',
            key: 'user_email',
        },
        {
            title: '手机号',
            dataIndex: 'user_phone',
            key: 'user_phone',
        },
        {
            title: '注册时间',
            dataIndex: 'user_creattime',
            key: 'user_creattime',
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record) => (
                <Space size="middle" key={record.user_id}>
                    <a onClick={()=>{showRow(record)}}>查看</a>
                    <a onClick={()=>{detailRow(record)}}>编辑</a>
                    <a onClick={()=>{delRow(record)}}>删除</a>
                </Space>
            ),
        },
    ];
    
    // 选择的数组
    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
        },
        getCheckboxProps: (record) => ({
            disabled: record.name === 'Disabled User',
            // Column configuration not to be checked
            name: record.name,
        }),
    };
    return (
        <div>
        <Table rowKey={record=>record.user_id} 
        rowSelection={{
                    type: 'checkbox',
                    ...rowSelection,
                }} columns={columns} dataSource={date}
                    pagination={{
                        pageSize: 4
            }} />
        <Modal  forceRender 
                        title="更改用户"
                        open={lookOpen}
                        confirmLoading={confirmLoading}
                        footer={[
                            <Button key='submit' type="primary" htmlType="submit" onClick={detailFinish} style={ {display:btn}}>
                               保存更改
                              </Button>,
                              <Button key='cancel' htmlType="button" onClick={handleCancel} style={{ marginLeft: "10px" }}>
                                取消
                              </Button>
                          ]}
                    >
                        <Form
                            form={form2}
                            labelCol={{
                            span: 4,
                            }}
                            wrapperCol={{
                            span: 14,
                            }}
                            layout="horizontal"
                            style={{
                            maxWidth: 600,
                            }}
                            disabled={componentDisabled}
                        >
                            
                            <Form.Item label="用户名称" name='user_name' initialValue={user_name}>
                            <Input />
                            </Form.Item>
                            <Form.Item label="用户账号" name='user_email' initialValue={user_email}>
                            <Input />
                            </Form.Item>
                            <Form.Item label="手机号" name='user_phone' initialValue={user_phone}>
                            <Input />
                            </Form.Item>
                            <Form.Item label="地址" name='user_address' initialValue={user_address}>
                            <Input />
                            </Form.Item>
                            <Form.Item label="生日" name='user_birthday' initialValue={dayjs(data||"2022-11-11", dateFormat)} >
                            <DatePicker  format={dateFormat} onChange={onChange} placeholder="请选择时间"/>
                            </Form.Item>
                            <Form.Item label="性别" >
                            <Radio.Group onChange={onChangeSex} value={sex}>
                                <Radio value={'男'}>男</Radio>
                                <Radio value={'女'}>女</Radio>
                                
                            </Radio.Group>
                            </Form.Item>
                            <Form.Item label="上传头像" valuePropName="fileList">
                            <Upload action="/api/upload" onChange={showUpload} listType="picture-card" fileList={fileList} >
                                <div>
                                <PlusOutlined />
                                <div
                                    style={{
                                    marginTop: 8,
                                    }}
                                >
                                    头像
                                </div>
                                </div>
                            </Upload>
                            </Form.Item>
                        </Form>
                    </Modal>        
    </div>
    )
};

const App = () => {
    const [date, setDate] = useState([]);
    const [messageApi, contextHolder] = message.useMessage();
    const { token } = theme.useToken();
    const listStyle = {
        textAlign: 'center',
        background: token.colorFillAlter,
        borderRadius: token.borderRadiusLG,
        marginTop: 16,
    };
    const handleChange = (value) => {
        console.log(`selected ${value}`);
      };
    return (
        <div>
            <AdvancedSearchForm setDate={setDate}/>
            <div style={listStyle}>
                <div style={{ lineHeight: '2rem', display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', height: '2rem', padding: '1rem' }}>
                    <h3>数据列表</h3>
                    <div>
                        <Select
                            defaultValue="批量操作"
                            onChange={handleChange}
                            options={[
                                { value: 'jack', label: '批量删除' },
                                { value: 'lucy', label: '批量XX' },
                            ]}
                        />
                    </div>
                </div>

                <div style={{ lineHeight: '20rem', }}>
                    <Divider />
                    <TableDetail setDate={setDate} date={date}/>
                </div>

            </div>
        </div>
    );
};
export default App;
